﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;

[RequireComponent(typeof(Light2D))]
public class ElectricLight:SimpleElectricalEquipment
{
    [SerializeField] private bool opend=true;
    [SerializeField] private float openSpeed=0.2f;
    [SerializeField] private float minFlickerFrequency=0.1f, maxFlickerFrequency=0.2f;
    [SerializeField] private float minIntDownValue=0.05f, maxIntDownValue=0.1f;

    private Light2D light;
    private float lightOpenLntensity;
    private bool opening=false;
    private float nextFlickerValue,nextIntDownValue;

   
    public override void Awake()
    {
        light = GetComponent<Light2D>();
        lightOpenLntensity = light.intensity;
        if (!opend)
        {
            light.intensity = 0;
        }
        base.Awake();
    }

    public override void Open()
    {
        SulNextFlicker();
        isOpen = true;
        opening = true;
    }

    public override void Close()
    {
        light.intensity = 0;
        isOpen = false;
        opend = false;
        opening = false;
    }

    private void Update()
    {
        if (opening)
        {
            light.intensity += Time.deltaTime * openSpeed;
            if (light.intensity>= nextFlickerValue)
            {
                light.intensity -= nextIntDownValue;
                SulNextFlicker();
            }
            if (light.intensity>=lightOpenLntensity)
            {
                light.intensity = lightOpenLntensity;
                opend = true;
                opening = false;
            }
        }
    }

    private void SulNextFlicker()
    {
        nextFlickerValue = Random.Range(minFlickerFrequency, maxFlickerFrequency) + light.intensity;
        nextIntDownValue = Random.Range(minIntDownValue, maxIntDownValue);
    }
}
